var main_1 = document.getElementById('main_1');
var myChart_1 = echarts.init(main_1);
var option_1,option_2,option_4;
var main_2 = document.getElementById('main_2');
var myChart_2 = echarts.init(main_2);
var main_4 = document.getElementById('main_4');
var myChart_4 = echarts.init(main_4);

// 自定义禁用地图区域上的点击变色效果的函数
myChart_1.on('click', function (params) {
myChart_1.dispatchAction({
    type: 'mapUnSelect',
    seriesIndex: 0,
    name: params.name
});
});

myChart_1.showLoading();
$.get('https://geo.datav.aliyun.com/areas_v3/bound/210200_full.json', function (geoJson) {
myChart_1.hideLoading();
echarts.registerMap('HK', geoJson);
myChart_1.setOption(
  (option_1 = {
    // title: {
    //   text: '大连市',
    //   left:'center',
    //   color:"white",
    //   // subtext: 'Data from Wikipedia',
    //   sublink:
    //     'http://zh.wikipedia.org/wiki/%E9%A6%99%E6%B8%AF%E8%A1%8C%E6%94%BF%E5%8D%80%E5%8A%83#cite_note-12'
    // },
    // tooltip: {
    //   trigger: 'item',
    //   formatter: '{b}<br/>{c} (p / km2)'
    // },\
    toolbox: {
      show: true,
      orient: 'vertical',
      left: 'right',
      top: 'center',
      feature: {
        dataView: { readOnly: false },
        restore: {},
        saveAsImage: {}
      }
    },
    visualMap: {
      min: 800,
      max: 50000,
      text: ['High', 'Low'],
      realtime: false,
      calculable: true,
      inRange: {
        color: ['lightskyblue', 'yellow', 'orangered']
      },
    },
    series: [
      {
        name: '大连市',
        type: 'map',
        map: 'HK',
        // silent: true // 直接取消悬停和点击事件
        label: {     //调整字体样式
          fontSize: 12,
          fontWeight:800,
          color:'#eeeeee',
          position: 'inside',
          show: false
        },
        itemStyle: {
            areaColor: 'black',   //改变默认背景色
            borderColor: '#adb2ae',
            borderWidth: 2.5, // 设置描边的粗细值
            emphasis: {
              areaColor: '#0f5ec2', // 鼠标悬停时的背景颜色
              label: {
                show: true,
                color: 'white' // 设置鼠标悬停时字体的颜色
              }
            }
        },
        data: [
          { name: '金州区', value: 20057.34 },
          { name: '湾仔', value: 15477.48 },
          { name: '东区', value: 31686.1 },
          { name: '南区', value: 6992.6 },
          { name: '油尖旺', value: 44045.49 },
          { name: '深水埗', value: 40689.64 },
          { name: '九龙城', value: 37659.78 },
          { name: '黄大仙', value: 45180.97 },
          { name: '观塘', value: 55204.26 },
          { name: '葵青', value: 21900.9 },
          { name: '荃湾', value: 4918.26 },
          { name: '屯门', value: 5881.84 },
          { name: '元朗', value: 4178.01 },
          { name: '北区', value: 2227.92 },
          { name: '大埔', value: 2180.98 },
          { name: '沙田', value: 9172.94 },
          { name: '西贡', value: 3368 },
          { name: '离岛', value: 806.98 }
        ],
        // 自定义名称映射
        nameMap: {
          'Central and Western': '中西区',
          Eastern: '东区',
          Islands: '离岛',
          'Kowloon City': '九龙城',
          'Kwai Tsing': '葵青',
          'Kwun Tong': '观塘',
          North: '北区',
          'Sai Kung': '西贡',
          'Sha Tin': '沙田',  
          'Sham Shui Po': '深水埗',
          Southern: '南区',
          'Tai Po': '大埔',
          'Tsuen Wan': '荃湾',
          'Tuen Mun': '屯门',
          'Wan Chai': '湾仔',
          'Wong Tai Sin': '黄大仙',
          'Yau Tsim Mong': '油尖旺',
          'Yuen Long': '元朗'
        }
      }
    ]
  })
);
});

option_1 && myChart_1.setOption(option_1);

// 获取年月日
const time_box_1 =document.querySelector('#time_read p:nth-of-type(1)')
const time_box_2 =document.querySelector('#time_read p:nth-of-type(2)')
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1  // 因为js中的月份是从0开始的，所以需要 +1
let day = date.getDate()

let formattedDate = `${year}年${month}月${day}日`
console.log(formattedDate)
time_box_1.innerHTML = formattedDate

//动态获取时分秒
function padNumber(number) {
if (number < 10) {
    return '0' + number
} else {
    return number
}
}

function updateTime() {
   let time = new Date()
   let hours = padNumber(time.getHours())
   let minutes = padNumber(time.getMinutes())
   let seconds = padNumber(time.getSeconds())

   let formattedTime = `${hours}时${minutes}分${seconds}秒`
   console.log(formattedTime);
   time_box_2.innerHTML = formattedTime
}

// 更新时间，并每秒重复一次
updateTime();
setInterval(updateTime, 1000);


//  根据血压，心跳和体温的正常阈值，生成的随机数
const heartRateElement = document.querySelector('#body_check div:nth-child(1) span')
const temperatureElement = document.querySelector('#body_check div:nth-child(4) span')
const bloodPressureElement = document.querySelector('#body_check div:nth-child(2) span')
let temperature = getRandomArbitrary(36.5, 37.1).toFixed(1)
let heartRate = Math.floor(getRandomArbitrary(60, 100))
let systolic = Math.floor(getRandomArbitrary(90, 120))
let diastolic = Math.floor(getRandomArbitrary(60, 80))

function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min
}

function getUpdatedValue(current, min, max, fluctuation) {
let newValue = parseFloat(current) + getRandomArbitrary(-fluctuation, fluctuation);
if (newValue < min) newValue = min
if (newValue > max) newValue = max
return newValue
}

setInterval(function() {
temperature = getUpdatedValue(temperature, 36.5, 37.1, 0.1).toFixed(1)
console.log("体温: " + temperature + " °C")
temperatureElement.innerHTML = temperature + '°C'
}, 5000)   // 体温每5秒更新一次

setInterval(function() {
heartRate = Math.floor(getUpdatedValue(heartRate, 60, 100, 5))
console.log("心率: " + heartRate + " bpm")
heartRateElement.innerHTML = heartRate + 'bpm'
}, 15000)  // 心率每15秒更新一次

setInterval(function() {
systolic = Math.floor(getUpdatedValue(systolic, 90, 120, 5))  /* 收缩压 */
diastolic = Math.floor(getUpdatedValue(diastolic, 60, 80, 5))  /* 舒张压 */
bloodPressureElement.innerHTML = systolic + "/" + diastolic + "mmHg"
console.log("血压: " + systolic + "/" + diastolic + " mmHg")
}, 30000)  // 血压每30秒更新一次


// 立即更新数据
function updateData() {
  temperature = getUpdatedValue(temperature, 36.5, 37.1, 0.1).toFixed(1);
  console.log("体温: " + temperature + " °C");
  temperatureElement.innerHTML = temperature + '°C';

  heartRate = Math.floor(getUpdatedValue(heartRate, 60, 100, 5));
  console.log("心率: " + heartRate + " bpm");
  heartRateElement.innerHTML = heartRate + 'bpm';

  systolic = Math.floor(getUpdatedValue(systolic, 90, 120, 5));
  diastolic = Math.floor(getUpdatedValue(diastolic, 60, 80, 5));
  bloodPressureElement.innerHTML = systolic + "/" + diastolic + "mmHg";
  console.log("血压: " + systolic + "/" + diastolic + " mmHg");
}

// 天气
WIDGET = {
  "CONFIG": {
    "layout": "1",
    "width": "450",
    "height": "160",
    "background": "4",
    "dataColor": "FFFFFF",
    "backgroundColor": "000000",
    "language": "zh",
    "borderRadius": "5",
    "key": "32b9f24a48ef4e27ad67250bd396e1fb"
  }
}




option_2= {
  color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
  // title: {
  //   text: 'Gradient Stacked Area Chart'
  // },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Line 1',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(128, 255, 165)'
          },
          {
            offset: 1,
            color: 'rgb(1, 191, 236)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      data: [600, 160, 552, 303, 160, 505, 166]
    },
    {
      name: 'Line 2',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(0, 221, 255)'
          },
          {
            offset: 1,
            color: 'rgb(77, 119, 255)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      data: [500, 501, 502, 503, 504, 505, 506]
    },
    {
      name: 'Line 3',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(55, 162, 255)'
          },
          {
            offset: 1,
            color: 'rgb(116, 21, 219)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      data: [400, 401, 402, 403, 404, 405, 406]
    },
    {
      name: 'Line 4',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(255, 0, 135)'
          },
          {
            offset: 1,
            color: 'rgb(135, 0, 157)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      data: [300, 301, 302, 303, 304, 305, 306]
    },
    {
      name: 'Line 5',
      type: 'line',
      stack: 'Total',
      smooth: true,
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      label: {
        show: true,
        position: 'top'
      },
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgb(255, 191, 0)'
          },
          {
            offset: 1,
            color: 'rgb(224, 62, 76)'
          }
        ])
      },
      emphasis: {
        focus: 'series'
      },
      data: [200, 201, 202, 203, 204, 205, 206]
    }
  ]
};
let initialData = option_2.series.map(series => series.data.slice());

function updateData_2() {
    option_2.series.forEach(function (series, seriesIndex) {
        series.data = initialData[seriesIndex].map(function (dataPoint) {
            // 在原始数据点的基础上增加一个介于-10到10之间的随机值
            return dataPoint + Math.random() * 50 - 10;
        });
    });
}

setInterval(function () {
    updateData_2();
    myChart_2.setOption(option_2);
}, 800);



     // 动态柱形图
     var dom = document.getElementById('main_3');
     var myChart_3 = echarts.init(dom);
     var data = [0, 0, 0, 0, 0]; // 开始时每个柱形的数据都设置为0
     var targetData = [80, 60, 36.5]; // 初始目标数据
     var thresholds = [[80, 120], [60, 100], [36.5, 37.1]]; // 设置每个阈值范围
  

    var option_3 = {
      title: {
          text: '安防检测系统'
      },
      xAxis: {
          max: 'dataMax'
      },
      yAxis: {
        
          type: 'category',
          data: ['血压检测', '心率检测', '体温检测', '应急报警'],
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 3, // 只显示最大的5个柱子
          axisLabel: {
           fontSize: 10 // 设置y轴文字大小为10
         }
      },
      series: [
          {
              realtimeSort: true,
             //  name: '热度',
              type: 'bar',
              data: data,
              label: {
                  show: true,
                  position: 'right',
                  valueAnimation: true
              }
          }
      ],
      legend: {
          show: true
      },
      animationDuration: 0,
      animationDurationUpdate: 1000, // 调整动画的持续时间，使其看起来更加动态
      animationEasing: 'linear',
      animationEasingUpdate: 'linear'
    };

    myChart_3.setOption(option_3);

    
    function run(i, interval) {
      setInterval(function () {
          // 更新目标数据，随机数的范围根据阈值来进行获取
          targetData[i] = Math.random() * (thresholds[i][1] - thresholds[i][0]) + thresholds[i][0];
  
          // 增加
          if (data[i] < targetData[i] ) {
              data[i] = data[i] + 1 > targetData[i] ? targetData[i] : data[i] + 1;
          }
          // 减少
          if (data[i] > targetData[i]) {
              data[i] = data[i] - 1 < targetData[i] ? targetData[i] : data[i] - 1;
          }
  
          // 对体温保留一位小数，对其他数据保留整数
          if (i === 2) {
              data[i] = parseFloat(data[i].toFixed(1));
          } else {
              data[i] = Math.round(data[i]);
          }
  
          myChart_3.setOption({
              series: [{
                  type: 'bar',
                  data: data
              }]
          });
      }, interval);
  }
  
  // 启动每个柱形图的更新
  run(0, 300); // 血压
  run(1, 350); // 心率
  run(2, 400); // 体温
    
    // 启动每个柱形图的更新
    run(0, 300); // 血压
    run(1, 350); // 心率
    run(2, 400); // 体温
  
    
    


       option_4 = {
    //     title: {   /* 标题 */
    //       textStyle:{fontSize:16},
    //       text: '艾吾科技-数据图',
    //       subtext: '有关内容如下',
    //       left: 'center',
    //       textStyle: {
    // fontSize: 15,}},
        
        // tooltip: {    /* 提示框 */
        //   trigger: 'item'
        // },
        // legend: {   
        //   orient: 'vertical',
        //   left: 'left'//小标识的位置
        // },
        series: [
          { 
            name: '数据',
            type: 'pie',
            radius: '50%',

            data: [
              { value: 1048, name: '血压安防检测' , label: { fontSize: 10 } },
              { value: 735, name: '心率安防检测' , label: { fontSize: 10 }},
              { value: 580, name: '体温安防检测', label: { fontSize: 10 } },
              { value: 0, name: '应急报警次数' , label: { fontSize: 10 }}
            ],
         
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart_4.setOption(option_4);






      var dom = document.getElementById('main_5');
      var myChart_5 = echarts.init(dom, null, {
        renderer: 'canvas',
        useDirtyRect: false
      });
      var app = {};
      
      var option_5;
  
      option_5 = {
    series: [
      {
        type: 'gauge',
        axisLine: {
          lineStyle: {
            width: 20,
            color: [
              [0.3, '#67e0e3'],
              [0.7, '#37a2da'],
              [1, '#fd666d']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -30,
          length: 15,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        axisLabel: {
          color: 'inherit',
          distance: -10,
          fontSize: 10
        },
        detail: {
          fontSize:13,
          valueAnimation: true,
          formatter: '{value} Mbps',
          color: 'inherit'
        },
        data: [
          {
            value: 70
          }
        ]
      }
    ]
  };
  setInterval(function () {
    myChart_5.setOption({
      series: [
        {
          data: [
            {
              value: +(Math.random() * 100).toFixed(2)
            }
          ]
        }
      ]
    });
  }, 2000);
  
      if (option_5 && typeof option_5 === 'object') {
        myChart_5.setOption(option_5);
      }
  
      window.addEventListener('resize', myChart_5.resize);



